<?php
// +----------------------------------------------------------------------
// | 用户模块业务逻辑
// +----------------------------------------------------------------------
// | Author: myh
// +----------------------------------------------------------------------
namespace app\admin\service;

use app\common\model\UserModel;
use Firebase\JWT\JWT;
use app\common\lib\msg\MessageContext;
use app\common\lib\msg\AliYunMessage;

class UserService
{   
    /**
     * 新增用户信息
     * @param  array  $data  新增的数据
     * @return int
     */
    public static function save($data){
        //验证该账号是否存在
        if(UserModel::getByAccount($data['account'])){
            return failure(config('error.er8')['code'],config('error.er8')['msg']);
        }

        //验证手机号是否存在
        if(UserModel::getByMobile($data['mobile'])){
            return failure(config('error.er9')['code'],config('error.er9')['msg']);
        }
        
        //默认会员等级
        $level = UserLevelService::list();
        $data['level'] = empty($level) ? 0 : $level[0]['id'];

        $data['password'] = createPassword($data['password']);
        $user = new UserModel;
        $user->save($data);
        return $user->id;
    }

    /**
     * 用户登录
     * @param  array  $data  请求参数
     * @return array
     */
    public static function login($data){
        if(isset($data['mobile']) && !empty($data['mobile'])){
            //手机号登录
            if($data['code'] != cache(MOBILE_CODE_.$data['mobile'])){
                return failure(config('error.er7')['code'],config('error.er7')['msg']);
            }
            $user = UserModel::getByMobile($data['mobile']);
            if(empty($user)){
                return failure(config('error.er10')['code'],config('error.er10')['msg']);
            }
            //验证码缓存清楚
            cache(MOBILE_CODE_.$data['mobile'],null);
        }else{
            //账号(包含手机号)密码登录
            $user = UserModel::getByMobile($data['account']);
            if(empty($user)){
                //如果输入的账号不是手机号，则通过账号字段查询
                $user = UserModel::getByAccount($data['account']);
            }
            //如果都为空，则抛出提示信息
            if(empty($user)){
                failure(config('error.er13')['code'],config('error.er13')['msg']);
            }

            //验证密码是否正确
            if(!comparePassword($data['password'],$user['password'])){
                failure(config('error.er11')['code'],config('error.er11')['msg']);
            }

        }

        if($user['status'] == 0){
            failure(config('error.er12')['code'],config('error.er12')['msg']);
        } 
       
        //下面是验证成功后的处理逻辑
        //登录成功后更新用户信息
        $user->is_first_login = 1;
        $user->login_time = date('Y-m-d H:i:s',time());
        $user->login_ip = getClientIp();
        $user->save();

        //生成token //composer require firebase/php-jwt   https://github.com/firebase/php-jwt
        $token = $user->toArray();
        //一天后过期
        $token['exp'] = time() + 24*3600;
       
        $jwt = JWT::encode($token,config('app.jwt_code_pc'),"HS256");
        
        return [
            'token' => $jwt,
            'is_first_login' => $user['is_first_login']
        ];
    }

    /**
     * 更新数据
     * @param  array  $data  更新数据
     * @return bool
     */
    public static function update($data){
        $user = UserModel::find($data['id']);
        if(!$user){
            return failure(config('error.er15')['code'],config('error.er15')['msg']);
        }

        //如果提交过来的账号跟数据库记录的账号不一样，说明当前提交过来的账号是修改过后的账号，因此这里需要验证码修改过的账号是否在数据库里面已经存在
        if(isset($data['account']) && $data['account'] !== $user->account){
            if(UserModel::getByAccount($data['account'])){
                //如果存在
                return failure(config('error.er13')['code'],config('error.er13')['msg']);
            }
        }
        if (isset($data['password'])) {
            $data['password'] = createPassword($data['password']);
        }

        return success($user->save($data));
    }

    /**
     * 更新密码
     * @param  array  $data  更新数据
     * @return array
     */
    public static function updatePassword($data){
        $user = UserModel::find($data['id']);
        if(!$user){
            return failure(config('error.er15')['code'],config('error.er15')['msg']);
        }
        $data['password'] = createPassword($data['password']);
        if($user->save($data)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 更新密码
     * @param  array  $data  更新数据
     * @return array
     */
    public static function updatePasswordByMobile($data){
        $user = UserModel::getByMobile($data['mobile']);
        if(!$user){
            return failure(config('error.er15')['code'],config('error.er15')['msg']);
        }
        $data['password'] = createPassword($data['password']);
        if($user->save($data)){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 删除
     * @param  string  $ids  需要删除数据的id
     */
    public static function destroy($ids){
        if(!empty($ids)){
            UserModel::destroy(explode(',',$ids));
        }
    }
    
    /**
     * 用户列表
     * @param  array  $param  请求参数
     * @return array
     */
    public static function page($param){
        $data = UserModel::page($param,['withoutField'=>'password']);

        foreach ($data['list']  as $k => $v) {
            $data['list'][$k]['status_text'] = UserModel::$status[$v['status']];
            $data['list'][$k]['level_name'] = UserLevelService::getLevelNameById($v['level']);
        }

        return success($data);
    }

    /**
     * 用户列表
     * @param  int  $id  用户ID
     * @return array
     */
    public static function info($id){
        $user = UserModel::find($id);
        $user['level_name'] = UserLevelService::getLevelNameById($user['level']);
        return success($user);
    }

    /**
     * 签到
     * @param  array  $data  请求参数
     * @return bool
     */
    public static function sign($data){
        Db::startTrans();
        try {
            //假设每次签到获取10积分，后面会完善签到功能
            //更新用户表的积分总数
            $user = UserModel::find($data['id']);
            $user->user_integral = $user->user_integral + 10;
            $user->save();

            //新增一条积分明细
            $integral['user_id'] = $data['id'];
            $integral['type'] = UserIntegralService::$signType;
            $integral['integral'] = 10;
            $integral['creator'] = $data['id'];
            UserIntegralService::save($integral);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }

    /**
     * 获取手机验证码
     * @param  string  $mobile  手机号
     * @param  string  $limit   位数
     * @return bool
    */
    public static function getMobileCode($mobile, $limit = 4){
        if($limit == 4){
            $code = rand(0000,9999);
        }else{
            $code = rand(000000,999999);
        }

        //如果手机验证码还没有过期，则提示不要重复发送
        if(cache(config('cachekey.mobile_code').$mobile)){
            serviceException(config('error.er3')['code'],config('error.er3')['msg']);
        }
        
        $msgCtx = new MessageContext(new AliYunMessage);
        if($msgCtx->sendMessage($mobile,$code)){
            cache(config('cachekey.mobile_code').$mobile,$code,60);
            return true;
        }else{
            return false;
        }
    }
    
    
}
